package com.booking.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.booking.bean.Food;
import com.booking.bean.Foodorder;
import com.booking.bean.Shop;
import com.booking.dao.ShopDAO;
import com.booking.service.ShopService;


@Service
public class ShopServiceImpl implements ShopService {

	@Autowired
	private ShopDAO shopDAO ;
	
	@Override
	public Foodorder addSorder(Foodorder forder, Food product) {
		boolean isHave = false; //用来标记有没有重复购物项  
        //拿到当前的购物项  
        Shop sorder = productToSorder(product);  
        //判断当前购物项是否重复，如果重复，则添加数量即可  
        if(forder.getShop() != null){
	        for(Shop old : forder.getShop()) {  
	            if(old.getFood().getId() == (sorder.getFood().getId())) {  
	                //购物项有重复，添加数量即可  
	                old.setNum(old.getNum() + sorder.getNum());  
	                isHave = true;  
	                break;  
	            }  
	        } 
        }
        //当前购物项在购物车中不存在，新添加即可  
        if(!isHave) {  
            forder.getShop().add(sorder);  
        }  
        return forder;  
	}

	@Override
	public Shop productToSorder(Food product) {
		  Shop sorder = new Shop();  
	        sorder.setName(product.getFoodname());  
	        sorder.setNum(1);  
	        sorder.setPrice(product.getPrice());  
	        sorder.setFood(product);  
	        sorder.setFoodid(product.getId());
	        
	        return sorder;  
	}

	@Override
	public Foodorder updateSorder(Shop sorder, Foodorder forder) {
		for( Shop temp : forder.getShop()) {
			if(temp.getFood().getId() ==(sorder.getFood().getId())) {
				temp.setNum(sorder.getNum());
			}
		}
		return forder;
	}

	@Override
	public Foodorder deleteSorder(Shop sorder, Foodorder forder) {
		int i = 0;
		for( Shop temp : forder.getShop()) {
			if(temp.getFood().getId() ==(sorder.getFood().getId())) {
				forder.getShop().remove(i);
			}
			i++;
		}
		return forder;
	}

	@Override
	public Foodorder deleteAll(Shop sorder, Foodorder forder) {
		forder.getShop().removeAll(forder.getShop());
		
		return forder;
	}

	@Override
	public List<Shop> queryShop(int id) {
		List<Shop> result = shopDAO.queryShop(id);
		return result;
	}

}
